package org.jeecg.modules.lab.util.wordUtil;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.lab.entrust.entity.*;
import org.jeecg.modules.lab.entrust.service.ILabEntrustItemsService;
import org.jeecg.modules.lab.items.record.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
@Slf4j
public class WordCreateUtils {

    @Autowired
    private ILabEntrustItemsService labEntrustItemsService;

    @Autowired
    private ILabItemsRecordSampleService labItemsRecordSampleService;

    @Autowired
    private ILabItemsRecordDeviceService labItemsRecordDeviceService;

    @Autowired
    private ILabItemsRecordNormService labItemsRecordNormService;

    @Autowired
    private ILabItemsRecordTargetService labItemsRecordTargetService;

    @Autowired
    private ILabItemsRecordPersonService labItemsRecordPersonService;

    private static final String folderPatha = "D:\\zhuiExperiment\\template";

    private static final String downlPathb = "D:\\opt\\upFiles\\labPdf\\";


    public String createWord(String itemId, String reportNum) throws IOException, IllegalAccessException, TemplateException {

        LabEntrustItems items = labEntrustItemsService.getById(itemId);
        if (items != null) {
            String folderPathb = downlPathb + reportNum;
            File file = new File(folderPathb);
            if (!file.exists()) {
                file.mkdir();
            }
            LabEntrustItems item = items;
            String itemName = item.getItemName();
            if (item.getItemName().contains("/")) {
                itemName = item.getItemName().replace("/", "-");
            }
            String task_item_id = item.getId();
            Map mapData = ronrew(itemName, task_item_id);
            Map itemData = (Map) mapData.get("data");
            replaceNull(itemData);
            String itmePath = itemName + ".xml";
            String fileUrl = folderPathb + "\\" + itemName + ".docx";
            parse(folderPatha, itmePath, fileUrl, itemData);
            WordToPdfUtils wordToPdfUtils = new WordToPdfUtils();
            String pdfUrl = folderPathb + "\\" + itemName + ".pdf";
            wordToPdfUtils.wordToPdf(fileUrl, pdfUrl);
            return pdfUrl;
        }
        return null;
    }


    /**
     * 通过委托id和项目id查询数据
     */
    public Map ronrew(String itemName, String task_item_id) throws IOException, IllegalAccessException {
        Map map1 = new HashMap();
        Map maps2 = new HashMap();
        originalRecord(map1, task_item_id, itemName);
        maps2.put("data", map1);

        return maps2;
    }

    /**
     * 原始记录的查询选择
     *
     * @param replacements
     * @param
     * @throws ParseException
     */
    public void originalRecord(Map replacements, String task_item_id, String itemName) throws IOException, IllegalAccessException {

        //todo 样品信息
        QueryWrapper<LabItemsRecordSample> samWrapper = new QueryWrapper<>();
        samWrapper.eq("task_item_id", task_item_id)
                .eq("field_input", "1");
        List<LabItemsRecordSample> labItemsRecordSampleList = labItemsRecordSampleService.list(samWrapper);
        for (LabItemsRecordSample sample : labItemsRecordSampleList) {
            String fileCode = sample.getFieldCode();
            String fileValue = sample.getFieldValue();
            if ("check_time".equals(fileCode) && fileValue != null && fileValue.contains("至")) {
                String[] parts = fileValue.split("至");
                if (parts.length == 2) {
                    String startDate = parts[0].substring(0, 10); // 获取起始日期部分
                    String endDate = parts[1].substring(0, 10); // 获取结束日期部分
                    String outputDateRange = "";
                    if (endDate == null || "".equals(endDate)) {
                        outputDateRange = startDate;
                    } else {
                        outputDateRange = startDate + "至" + endDate;
                    }
                    replacements.put(fileCode, outputDateRange);
                } else {
                    replacements.put(fileCode, fileValue);
                }
            } else {
                replacements.put(fileCode, fileValue);
            }

        }
        //todo 设备信息
        List<LabItemsRecordDevice> labItemsRecordDevicesList = labItemsRecordDeviceService.byEntrustItemId(task_item_id);
        String devName = "";
        for (LabItemsRecordDevice ssa : labItemsRecordDevicesList) {
            if (devName != "") {
                devName += "\n";
            }
            if (ssa.getDevName() != null && ssa.getDevName() != "") {
                devName += ssa.getDevName() + " ";
            }
            if (ssa.getDevNum() != null && ssa.getDevNum() != "") {
                devName += ssa.getDevNum() + " ";
            }
            if (ssa.getDevValidity() != null && ssa.getDevValidity() != "") {
                devName += ssa.getDevValidity();
            }
        }
        replacements.put("dev_name", devName);
        //todo 检测条件
        QueryWrapper<LabItemsRecordNorm> normWrapper = new QueryWrapper<>();
        normWrapper.eq("task_item_id", task_item_id)
                .eq("field_input", "1");
        List<LabItemsRecordNorm> labItemsRecordNormList = labItemsRecordNormService.list(normWrapper);
        for (LabItemsRecordNorm norm : labItemsRecordNormList) {
            replacements.put(norm.getFieldCode(), norm.getFieldValue());
        }

        //todo 第四部分的原始记录结果
        QueryWrapper<LabItemsRecordTarget> targetWrapper = new QueryWrapper<>();
        targetWrapper.eq("task_item_id", task_item_id)
                .eq("field_input", "1");
        List<LabItemsRecordTarget> labItemsRecordTargetList = labItemsRecordTargetService.list(targetWrapper);
        for (LabItemsRecordTarget target : labItemsRecordTargetList) {
            replacements.put(target.getFieldCode(), target.getFieldValue());
        }
        //todo 第五部分的原始记录签名
        QueryWrapper<LabItemsRecordPerson> personWrapper = new QueryWrapper<>();
        personWrapper.eq("task_item_id", task_item_id)
                .eq("field_input", "1");
        List<LabItemsRecordPerson> labItemsRecordPersonList = labItemsRecordPersonService.list(personWrapper);
        for (LabItemsRecordPerson person : labItemsRecordPersonList) {
            String fielCode = person.getFieldCode();
            String s = "";
            if (person.getFieldValue() != null) {
                String[] split = person.getFieldValue().split(",");
                s = split[0];
            } else {
                s = person.getFieldValue();
            }

            if ("check_person".equals(fielCode) || "person_value1".equals(fielCode)) {
                this.electricSign(fielCode, s, replacements);
            } else if ("audit_person".equals(fielCode) || "person_value2".equals(fielCode)) {
                this.electricSign(fielCode, person.getFieldValue(), replacements);
            }
        }

    }


    /**
     * 替换检测人，复核人的签名为电子签名
     *
     * @param fielCode          检测人/复核人
     * @param reviewPersonFiled 签名
     * @param map1              存放数据的
     * @return
     * @throws IOException
     * @throws IllegalAccessException
     */
    public void electricSign(String fielCode, String reviewPersonFiled, Map map1) throws IOException, IllegalAccessException {
        //图片位置
        String path = "D:\\zhuiExperiment\\picture\\";
        /*检测人不为空，则将检测人名字去匹配电子签名*/
//        if (fielCode != null) {
//            List<LoginUser> userList = labEntrustService.getUserList();
//            if ("check_person".equals(fielCode) || "person_value1".equals(fielCode)) {
//                if ("".equals(reviewPersonFiled) || reviewPersonFiled == null) {
//                    String realPath = path + "签名.jpg";
//                    File file = new File(realPath);
//                    FileInputStream fin4 = new FileInputStream(file);
//                    byte[] bytes4 = new byte[fin4.available()];
//                    fin4.read(bytes4);
//                    fin4.close();
//                    BASE64Encoder encoder4 = new BASE64Encoder();
//                    map1.put(fielCode, encoder4.encode(bytes4));
//                } else {
//                    for (int i = 0; i < userList.size(); i++) {
//                        LoginUser user = userList.get(i);
//                        if (user.getRealname().equals(reviewPersonFiled)) {
//                            if (!"".equals(user.getTpicture()) && user.getTpicture() != null) {
//                                String realPath = user.getTpicture();
//                                File file = new File(realPath);
//                                FileInputStream fin4 = new FileInputStream(file);
//                                byte[] bytes4 = new byte[fin4.available()];
//                                fin4.read(bytes4);
//                                fin4.close();
//                                BASE64Encoder encoder4 = new BASE64Encoder();
//                                map1.put(fielCode, encoder4.encode(bytes4));
//                            } else {
//                                String realPath = path + "签名.jpg";
//                                File file = new File(realPath);
//                                FileInputStream fin4 = new FileInputStream(file);
//                                byte[] bytes4 = new byte[fin4.available()];
//                                fin4.read(bytes4);
//                                fin4.close();
//                                BASE64Encoder encoder4 = new BASE64Encoder();
//                                map1.put(fielCode, encoder4.encode(bytes4));
//                            }
//                            break;
//                        }
//                    }
//                }
//            } else if ("audit_person".equals(fielCode) || "person_value2".equals(fielCode)) {
//                if ("".equals(reviewPersonFiled) || reviewPersonFiled == null) {
//                    String realPath = path + "签名.jpg";
//                    File file = new File(realPath);
//                    FileInputStream fin4 = new FileInputStream(file);
//                    byte[] bytes4 = new byte[fin4.available()];
//                    fin4.read(bytes4);
//                    fin4.read(bytes4);
//                    fin4.close();
//                    BASE64Encoder encoder4 = new BASE64Encoder();
//                    map1.put(fielCode, encoder4.encode(bytes4));
//                } else {
//                    for (int i = 0; i < userList.size(); i++) {
//                        if (userList.get(i).getRealname().equals(reviewPersonFiled)) {
//                            if (!"".equals(userList.get(i).getTpicture()) && userList.get(i).getTpicture() != null) {
//                                //String realPath = path+reviewPersonFiled+"签名.jpg";
//                                String realPath = userList.get(i).getTpicture();
//                                File file = new File(realPath);
//                                FileInputStream fin4 = new FileInputStream(file);
//                                byte[] bytes4 = new byte[fin4.available()];
//                                fin4.read(bytes4);
//                                fin4.read(bytes4);
//                                fin4.close();
//                                BASE64Encoder encoder4 = new BASE64Encoder();
//                                map1.put(fielCode, encoder4.encode(bytes4));
//                            } else {
//                                String realPath = path + "签名.jpg";
//                                File file = new File(realPath);
//                                FileInputStream fin4 = new FileInputStream(file);
//                                byte[] bytes4 = new byte[fin4.available()];
//                                fin4.read(bytes4);
//                                fin4.read(bytes4);
//                                fin4.close();
//                                BASE64Encoder encoder4 = new BASE64Encoder();
//                                map1.put(fielCode, encoder4.encode(bytes4));
//                            }
//                            break;
//                        }
//                    }
//                }
//
//            }
//
//        }
    }


    public void parse(String templateDir, String templateName, String excelPath, Map<String, Object> data) throws IOException, freemarker.template.TemplateException {
        //初始化工作
        Configuration cfg = new Configuration();
        //设置默认编码格式为UTF-8
        cfg.setDefaultEncoding("gbk");
        //全局数字格式
        cfg.setNumberFormat("0");
        //设置模板文件位置
        cfg.setDirectoryForTemplateLoading(new File(templateDir));
        cfg.setObjectWrapper(new DefaultObjectWrapper());
        //加载模板
        freemarker.template.Template template = cfg.getTemplate(templateName, "utf-8");
        Writer writer = null;
        try {
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(excelPath), "UTF-8"));
            template.process(data, writer);

            writer.flush();
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    /**
     * 替换NULL为""
     */
    public void replaceNull(Map data) {
        Set keys = data.keySet();
        for (Object key : keys) {
            if (data.get(key) == null) {
                data.put(key, "");
            }
        }
    }

}
